package com.study.servlet.admin;

import com.study.dao.CountryInfoDAO;
import com.study.dao.impl.CountryInfoDAOImpl;
import com.study.pojo.CountryInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @PackgeName: com.study.servlet.admin
 * @ClassName: CountryAddServlet
 * @Author: 严志祥
 * Date: 2022-05-06 14:43
 * project name: web_project_medal
 * @Version:
 * @Description:
 */
@WebServlet("/admin/country-update.let")
public class CountryUpdateServlet extends HttpServlet {
    private CountryInfoDAO dao = new CountryInfoDAOImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.reset();
        resp.setContentType("application/json;charset=utf-8");
        try {
            CountryInfo e = new CountryInfo();
            String code = req.getParameter("countryCode");
            if (code == null || "".equals(code)) {
                throw new ServletException("国家编码不能为空");
            }
            if (!code.matches("^\\w+$")) {
                throw new ServletException("国家编码只能是字母");
            }
            e.setCountryUri(req.getParameter("countryUri"));
            e.setCountryCode(code);
            e.setCountryNameCn(req.getParameter("countryNameCn"));
            e.setCountryNameEn(req.getParameter("countryNameEn"));
            e.setCountryName(req.getParameter("countryName"));


            try {
                dao.updateById(e);
                resp.getWriter().print("{\"ok\":true}");
            } catch (Exception ex) {
                throw new ServletException("国家代码重复", ex);
            }
        }catch (Exception e){
            resp.getWriter().print("{\"ok\":false,\"msg\":\""+e.getMessage()+"\"}");
        }
        resp.flushBuffer();
    }
}
